import React, { Component } from 'react';
import LoaderHelper from './loaderHelper';
import DomHelper from '../domHelper';
import { PAGE_BACKGROUND, DEFAULT_PAGE_COLOR } from '../../../../../../utils/consts';

class BackgroundLoader extends Component {
    componentDidMount() {
        const { page } = this.props;
        let pageData = page;
        // 新增页面时构建数据
        if (!pageData) {
            pageData = {
                custom: 1,
                url: window.is.CONST.media_src,
                md5: "",
                backgroundColor: ""
            };
        }

        this.loadMainImg(pageData);
    }

    componentWillReceiveProps(nextProps) {
    	if (nextProps.page !== this.props.page) {
    		this.loadMainImg(nextProps.page)
    	}
    }

    loadMainImg(pageData) {
        let defaultWidth = window.is.CONST.editor_width,
            defaultHeight = window.is.CONST.editor_height;

        // 默认为显示图片
        // let isCustom = pageData.custom === undefined ? 1 : pageData.custom;
        const isCustom = pageData && pageData.page_background && parseInt(pageData.page_background.custom);
    	const bacImg = isCustom ? pageData.page_background.url : window.is.CONST.media_src;
        let width = (isCustom == 1) ? defaultWidth : PAGE_BACKGROUND.SIZE.WIDTH,
            height = (isCustom == 1) ? defaultHeight : PAGE_BACKGROUND.SIZE.HEIGHT;

        let data = {
            opacity: 1,
            offset_x: 0,
            offset_y: 0,
            offset_z: -1,
            width: width,
            height: height,
            stereoRotateX: 0,
            stereoRotateY: 0,
            stereoRotateZ: 0,
            nonSelectable: true,
            url: bacImg,
            color: pageData.backgroundColor || DEFAULT_PAGE_COLOR
        };

        // 清除原有背景效果
        if (DomHelper.mainImgMesh){
            DomHelper.scene.remove(DomHelper.mainImgMesh);
        }

        // 背景为颜色
        if (0 == isCustom){
            DomHelper.mainImgMesh = this.solidColorMeshCreator(data, true);
            DomHelper.scene.add(DomHelper.mainImgMesh);
        // 背景为图片
        } else {
            LoaderHelper.imageGeometryLoader(null, data, false, true);
        }
    }

    // 纯色图形创建器
    solidColorMeshCreator(widget, isMainImg) {
        let canvas = LoaderHelper.canvasCreator({ data: widget });
        let texture = new THREE.CanvasTexture(canvas);
        let material = new THREE.MeshBasicMaterial({ map: texture, side: THREE.DoubleSide, transparent: !isMainImg });
        let geometry = new THREE.PlaneGeometry(widget.width, widget.height);
        let mesh = LoaderHelper.meshCreator(null, THREE.PlaneGeometry, {}, widget, geometry, material);
        return mesh;
    }

    render() {
        return (<div />)
    }
}

export default BackgroundLoader;
